<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SystemSetting;
use App\Models\LogisticsCompany;
use App\Traits\LogsActivity;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminSystemSettingController extends Controller
{
    use LogsActivity;
    /**
     * 显示系统设置页面
     */
    public function index(Request $request)
    {
        $activeGroup = $request->get('group', 'basic');
        
        // 获取所有设置，按分组和排序组织
        $settings = SystemSetting::orderBy('group')
            ->orderBy('sort_order')
            ->get()
            ->groupBy('group');

        // 转换为前端友好的格式
        $formattedSettings = $settings->map(function ($groupSettings, $groupName) {
            return [
                'name' => $groupName,
                'label' => $this->getGroupLabel($groupName),
                'settings' => $groupSettings->map(function ($setting) {
                    return [
                        'id' => $setting->id,
                        'key' => $setting->key,
                        'value' => $setting->value,
                        'type' => $setting->type,
                        'label' => $setting->label,
                        'description' => $setting->description,
                        'is_public' => $setting->is_public,
                    ];
                })->values(),
            ];
        })->values();

        // 添加物流公司标签页（即使没有对应的系统设置）
        if (!$formattedSettings->contains('name', 'logistics')) {
            $formattedSettings->push([
                'name' => 'logistics',
                'label' => '物流公司',
                'settings' => collect([])
            ]);
        }

        // 获取物流公司数据
        $logisticsCompanies = LogisticsCompany::ordered()->get();

        return Inertia::render('Admin/SystemSettings/Index', [
            'settings' => $formattedSettings,
            'activeGroup' => $activeGroup,
            'logisticsCompanies' => $logisticsCompanies,
        ]);
    }

    /**
     * 更新系统设置
     */
    public function update(Request $request)
    {
        $validated = $request->validate([
            'settings' => 'required|array',
            'settings.*.key' => 'required|string|exists:system_settings,key',
            'settings.*.value' => 'nullable',
        ]);

        $updatedKeys = [];
        foreach ($validated['settings'] as $settingData) {
            SystemSetting::set($settingData['key'], $settingData['value']);
            $updatedKeys[] = $settingData['key'];
        }

        // 记录日志
        $this->logActivity(
            action: 'update',
            module: 'system-settings',
            description: '更新系统设置: ' . implode(', ', $updatedKeys)
        );

        return redirect()->back()->with('success', '系统设置已更新');
    }

    /**
     * 获取分组标签
     */
    private function getGroupLabel(string $group): string
    {
        return match($group) {
            'basic' => '基础设置',
            'shop' => '商城设置',
            'shipping' => '物流配送',
            'logistics' => '物流公司',
            'seo' => 'SEO 优化',
            default => $group,
        };
    }
}
